package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private UserMapper userMapper;


    @Autowired
    private ShoopingCatMapper shoopingCatMapper;


    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    //TODD高德地图相关设置
    @Value("${sky.shop.address}")
    private String Address;

    @Value("${sky.gaode.key}")
    private String key;

    /*@Value("${sky.gaode.sig}")
    private String sig;*/

    /*用户下单*/
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO orderSubmitDTO) {

        //处理异常 (地址为空 购物车也为空)
        AddressBook addressBookById = addressBookMapper.getById(orderSubmitDTO.getAddressBookId());
        if (addressBookById == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBookById.getCityName() + addressBookById.getDistrictName() + addressBookById.getDetail());

        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoopingCatMapper.getList(shoppingCart);
        if (shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO, orders);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBookById.getPhone());
        orders.setConsignee(addressBookById.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(addressBookById.getProvinceName() + addressBookById.getCityName() + addressBookById.getDistrictName() + addressBookById.getDetail());


        orderMapper.insert(orders);

        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });


        orderDetailMapper.insertBatch(orderDetailList);
        //确定支付成功之后清空购物车
        shoopingCatMapper.delete(BaseContext.getCurrentId());


        return OrderSubmitVO.builder().id(orders.getId()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).build();
    }


    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        //User user = userMapper.getById(userId);

        JSONObject jsonObject = new JSONObject();
        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Orders orders = orderMapper.getByUserId(userId);
        paySuccess(orders.getNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket推送消息给客户端 三个参数 type orderId content
        Map map = new HashMap<>();
        map.put("type", 1);// 1表示来单提醒   2 表示催单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }


    /*查询历史订单*/
    @Override
    public PageResult pageQueryOrders(int page, int pageSize, String status) {
        PageHelper.startPage(page, pageSize);
        //进行基础查询
        List<Orders> ordersList = orderMapper.pageQueryOrders(BaseContext.getCurrentId(), status);
        Page<Orders> pageInfo = (Page<Orders>) ordersList;
        //封装返回结果
        List<OrderVO> orderVOList = new ArrayList<>();

        if (pageInfo.getTotal() > 0 && pageInfo != null) {
            ordersList.forEach(item -> {
                //根据订单id查询订单明显
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(item.getId());

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                //设置返回结果中的订单明细
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            });
        }

        return new PageResult(pageInfo.getTotal(), orderVOList);
    }

    /**
     * 根据订单ID查询订单详情。
     * 该方法通过ID从数据库中检索订单信息，并将其转换为OrderVO对象，包括订单的详细信息。
     * 如果找到了对应的订单，将订单详情列表设置到OrderVO中，以便返回给调用者一个完整的订单视图。
     *
     * @param id 订单的唯一标识符。
     * @return 包含订单详细信息的OrderVO对象。如果找不到对应的订单，则返回null。
     */
    /*根据id查询订单详情*/
    @Override
    public OrderVO getOrderDetailById(Long id) {
        // 通过订单ID查询数据库中的订单信息
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        // 如果找到了订单，进行进一步处理
        if (orders != null) {
            // 查询该订单的所有详细信息
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
            // 将订单实体类的属性复制到订单VO对象中
            BeanUtils.copyProperties(orders, orderVO);
            // 设置订单的详细信息列表
            orderVO.setOrderDetailList(orderDetailList);
        }
        // 返回转换后的订单VO对象，可能为空
        return orderVO;
    }

    /*取消订单*/
    @Override
    public void cancelOrder(Long id) {
        //先查看订单是否存在并且
        Orders orders = orderMapper.getById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orders.getStatus() > 2) {//判断状态 待接单状态才能取消
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //取消订单
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            Orders cancelOrder = Orders.builder()
                    .id(id)
                    .status(Orders.CANCELLED)
                    .cancelReason("用户取消")
                    .cancelTime(LocalDateTime.now())
                    .payStatus(Orders.REFUND)
                    .build();
            orderMapper.update(cancelOrder);
        }
    }

    /*再来一单*/
    @Override
    public void repetition(Long id) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //把订单信息复制给购物车
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(
                item -> {
                    ShoppingCart shoppingCart = new ShoppingCart();
                    BeanUtils.copyProperties(item, shoppingCart, "id");
                    shoppingCart.setUserId(userId);
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    return shoppingCart;
                }
        ).collect(Collectors.toList());

        //批量添加到购物车
        shoopingCatMapper.insertBatch(shoppingCartList);


    }

    /*订单查询*/
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<Orders> ordersList = orderMapper.conditionSearch(ordersPageQueryDTO);
        if (ordersList == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Page<Orders> pageInfo = (Page<Orders>) ordersList;

        //自定义返回结果
        List<OrderVO> orderVOList = getOrdersVoList(pageInfo);


        return new PageResult(pageInfo.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrdersVoList(Page<Orders> pageInfo) {

        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = pageInfo.getResult();
        if (ordersList.size() > 0 && ordersList != null) {
            //循环将订单封装到OrderVO中
            ordersList.forEach(item -> {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                orderVO.setOrderDishes(getOrderDishes(item));
                orderVOList.add(orderVO);
            });
        }

        return orderVOList;
    }

    private String getOrderDishes(Orders item) {
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(item.getId());
        if (byOrderId == null) {
            return null;
        }

        List<String> orderDishes = byOrderId.stream().map(
                x -> {
                    return x.getName() + "*" + x.getNumber() + ";";
                }
        ).collect(Collectors.toList());

        return orderDishes.toString();
    }

    /*查询各个订单状态的数量*/
    @Override
    public OrderStatisticsVO getBystatus() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.getBystatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.getBystatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getBystatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /*接单*/
    @Override
    public void confirm(OrderVO orderVO) {
        orderVO.setStatus(Orders.CONFIRMED);
        orderMapper.update(orderVO);
    }

    /*拒绝接单*/
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //查询订单是否处于待接单的状态 才能拒绝订单
        Orders orders = isDecideID(ordersRejectionDTO.getId());
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        Orders ordersDB = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, ordersDB);//有两个 id 和拒绝信息
        ordersDB.setStatus(Orders.CANCELLED);//设置拒绝订单状态
        ordersDB.setCancelTime(LocalDateTime.now());//设置取消时间
        ordersDB.setPayStatus(Orders.REFUND);
        orderMapper.update(ordersDB);

    }

    /*客户端取消订单*/
    @Override
    public void cancelAdminOrder(OrdersCancelDTO ordersCancelDTO) {
        //判断订单支付状态
        Orders orders = isDecideID(ordersCancelDTO.getId());
        if (orders.getPayStatus() == Orders.UN_PAID) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders ordersDB = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, ordersDB);
        ordersDB.setStatus(Orders.CANCELLED);
        ordersDB.setCancelTime(LocalDateTime.now());
        ordersDB.setPayStatus(Orders.REFUND);
        orderMapper.update(ordersDB);
    }


    @Override
    public void delivery(Long id) {
        Orders orders = isDecideID(id);
        //只能是待派送的订单才能派送
        if (orders.getStatus() != Orders.CONFIRMED && orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders ordersDB = new Orders().builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryStatus(1)
                .estimatedDeliveryTime(LocalDateTime.now().plusHours(1))
                .build();
        orderMapper.update(ordersDB);
    }

    /*完成订单*/
    @Override
    public void complete(Long id) {
        Orders orders = isDecideID(id);
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS && orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders ordersDB = new Orders().builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.update(ordersDB);

    }

    /*用户催单*/
    @Override
    public void reminder(Integer id) {
        Orders orders = isDecideID(Long.valueOf(id));
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap<>();
        map.put("type", 2);// 1表示来单提醒   2 表示催单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号:" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    //根据id查询订单
    private Orders isDecideID(Long id) {
        Orders orders = orderMapper.getById(id);
        return orders;
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", Address);
        map.put("output", "json");
        map.put("ak", key);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
